// 照片质量检测API调用服务
// 提供基于机器学习模型的照片质量检测和合格率统计功能

import MesHelp from '../Http/MesHelp'

// 照片质量检测API服务类
class PhotoQualityService {
    
    /**
     * 单张照片质量检测
     * @param {File} imageFile - 照片文件
     * @param {Object} options - 检测选项
     * @returns {Promise<Object>} 检测结果
     */
    static async detectPhotoQuality(imageFile: File, options: any = {}): Promise<any> {
        try {
            // 将文件转换为FormData
            const formData = new FormData();
            formData.append('imageFile', imageFile);
            formData.append('qualityThreshold', (options.qualityThreshold || 0.5).toString());
            formData.append('sessionId', options.sessionId || crypto.randomUUID());
            
            const result = await MesHelp.post('/api/PhotoQuality/detect', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                timeout: 60000 // 60秒超时
            });
            
            return result;
        } catch (error) {
            console.error('照片质量检测失败:', error);
            throw error;
        }
    }
    
    /**
     * 批量照片质量检测
     * @param {File[]} imageFiles - 照片文件数组
     * @param {Object} options - 批量处理选项
     * @returns {Promise<Object>} 批量检测结果
     */
    static async detectBatchPhotoQuality(imageFiles: File[], options: any = {}): Promise<any> {
        try {
            const formData = new FormData();
            
            // 添加所有照片文件
            imageFiles.forEach((file, index) => {
                formData.append(`Photos[${index}]`, file);
            });
            
            formData.append('qualityThreshold', (options.qualityThreshold || 0.5).toString());
            formData.append('options', JSON.stringify({
                continueOnError: options.continueOnError !== false,
                maxConcurrency: options.maxConcurrency || 10
            }));
            
            const result = await MesHelp.post('/api/PhotoQuality/detect/batch', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                timeout: 120000 // 120秒超时（批量处理需要更长时间）
            });
            
            return result;
        } catch (error) {
            console.error('批量质量检测失败:', error);
            throw error;
        }
    }
    
    /**
     * 获取质量统计信息
     * @param {Object} queryParams - 查询参数
     * @returns {Promise<Object>} 统计信息
     */
    static async getQualityStatistics(queryParams: any = {}): Promise<any> {
        try {
            const requestData = {
                startDate: queryParams.startDate || null,
                endDate: queryParams.endDate || null,
                groupBy: queryParams.groupBy || 'day'
            };
            
            const result = await MesHelp.post('/api/PhotoQuality/statistics', requestData);
            return result;
        } catch (error) {
            console.error('获取统计信息失败:', error);
            throw error;
        }
    }
    
    /**
     * 获取检测历史记录
     * @param {Object} queryParams - 查询参数
     * @returns {Promise<Object>} 历史记录
     */
    static async getDetectionHistory(queryParams: any = {}): Promise<any> {
        try {
            const requestData = {
                startDate: queryParams.startDate || null,
                endDate: queryParams.endDate || null,
                isQualified: queryParams.isQualified || null,
                minConfidence: queryParams.minConfidence || null,
                maxConfidence: queryParams.maxConfidence || null,
                pageIndex: queryParams.pageIndex || 0,
                pageSize: queryParams.pageSize || 20
            };
            
            const result = await MesHelp.post('/api/PhotoQuality/history', requestData);
            return result;
        } catch (error) {
            console.error('获取检测历史失败:', error);
            throw error;
        }
    }
    
    /**
     * 获取模型状态
     * @returns {Promise<Object>} 模型状态信息
     */
    static async getModelStatus(): Promise<any> {
        try {
            const result = await MesHelp.get('/api/PhotoQuality/status');
            return result;
        } catch (error) {
            console.error('检查模型状态失败:', error);
            throw error;
        }
    }
}

// TypeScript 类型定义
interface PhotoQualityRequest {
    imageData: number[];
    fileName?: string;
    imageFormat?: string;
    qualityThreshold?: number;
    sessionId?: string;
}

interface PhotoQualityResponse {
    detectionId: string;
    imageFileName: string;
    isQualified: boolean;
    confidence: number;
    predictedLabel: string;
    qualityScore: number;
    allScores: LabelScore[];
    processingTimeMs: number;
    timestamp: string;
    qualityThreshold: number;
    error?: string;
}

interface BatchPhotoQualityResponse {
    results: PhotoQualityResponse[];
    totalCount: number;
    qualifiedCount: number;
    unqualifiedCount: number;
    passRate: number;
    processingTimeMs: number;
    timestamp: string;
}

interface LabelScore {
    label: string;
    score: number;
}

interface QualityStatistics {
    totalDetections: number;
    qualifiedCount: number;
    unqualifiedCount: number;
    passRate: number;
    averageConfidence: number;
    minConfidence: number;
    maxConfidence: number;
    qualityDistribution: QualityDistribution[];
    timeDistribution: TimeDistribution[];
    recentTrends: QualityTrend[];
}

interface QualityDistribution {
    isQualified: boolean;
    count: number;
    percentage: number;
    averageConfidence: number;
}

interface TimeDistribution {
    time: string;
    count: number;
}

interface QualityTrend {
    date: string;
    totalCount: number;
    qualifiedCount: number;
    passRate: number;
    averageConfidence: number;
}

// 导出服务类供其他模块使用

// 导出服务类供其他模块使用
export { PhotoQualityService };
export type {
    PhotoQualityRequest,
    PhotoQualityResponse,
    BatchPhotoQualityResponse,
    QualityStatistics,
    LabelScore,
    QualityDistribution,
    TimeDistribution,
    QualityTrend
};
